import WsUtils, { WsCode } from "./WsUtils"

/**
 * 用户代理类
 */
export default class UserProxy {
    private static _instance: UserProxy = null
    public static get instance() {
        if (!this._instance) {
            this._instance = new UserProxy()
        }
        return this._instance
    }

    /** 用户ID */
    private _userId: number = 0
    public get userId() {
        if (this._userId == 0) {
            this._userId = cc.sys.localStorage.getItem('user_id')
            if (!this._userId) {
                this._userId = 0
            }
        }
        return this._userId
    }
    public set userId(v: number) { this._userId = v }

    /** 用户信息 */
    private _userInfo: UserInfo = null
    public get userInfo(): UserInfo { return this._userInfo }
    public set userInfo(v) { this._userInfo = v }

    // ------------------------------网络接口------------------------------
    /** 请求注册 */
    reqRegister() {
        WsUtils.send(WsCode.USER_REGISTER_REQ)
        cc.log('请求注册')
    }

    /** 请求注册回调 */
    respRegister(data) {
        this.userId = data
        cc.sys.localStorage.setItem('user_id', this.userId)
        cc.log('注册成功, userId = ' + this.userId)
    }

    /** 请求登录 */
    reqLogin() {
        WsUtils.send(WsCode.USER_LOGIN_REQ, this.userId)
        cc.log('请求登录')
    }

    /** 请求登录回调 */
    respLogin(data) {
        this.userInfo = new UserInfo(data)
        cc.log('登录成功', this.userInfo)
    }
}

/**
 * 用户信息
 */
class UserInfo {
    /** 用户id */
    private _id: number = null
    public get id() { return this._id }
    public set id(v: number) { this._id = v }

    /** QQ token */
    private _qq: string = null
    public get qq() { return this._qq }
    public set qq(v: string) { this._qq = v }

    /** WX token */
    private _wx: string = null
    public get wx() { return this._wx }
    public set wx(v: string) { this._wx = v }

    constructor(data) {
        this.id = data.id
        this.qq = data.qq
        this.wx = data.wx
    }
}
